// 管理账号信息
const USERS_KEY = "USERS_KEY"; //用户标识

const USERS_NAME = "USERS_NAME"; //用户姓名

const WEBSITE = "WEBSITE"; //位置

const TOKEN_KEY = "TOKEN_KEY"; //token

const TASK_LIST_KEY = "TASK_LIST_KEY"; //工作列表key

const TASK_DETAIL_KEY = "TASK_DETAIL_KEY"; //地图

const TIPS_KEY = "TIPS_KEY"; //建议

const SAMPLE_TYPE = {
  "1": "正常样",
  "2": "盲样",
  "3": "平行样",
  "4": "加标样",
  "5": "空白样",
  "6": "实验室比对"
};

const PAGE_DATA = []; //页面数据

// 获取本地用户名字
const getUserName = function() {
  let ret = "";
  ret = uni.getStorageSync(USERS_NAME);
  if (!ret) {
    ret = "{}";
  }
  return JSON.parse(ret);
};

// 保存用户名字
const setUserName = function(userInfo) {
  uni.setStorageSync(USERS_NAME, JSON.stringify(userInfo));
};

// 获取本地用户数据
const getUsers = function() {
  let ret = "";
  ret = uni.getStorageSync(USERS_KEY);
  if (!ret) {
    ret = "{}";
  }
  return JSON.parse(ret);
};

const getUserId = function() {
  let user = getUsers();
  return user.id;
};

// 保存用户
const addUser = function(userInfo) {
  uni.setStorageSync(USERS_KEY, JSON.stringify(userInfo));
};

// 获取 token
const getToken = function() {
  let ret = uni.getStorageSync(TOKEN_KEY);
  return ret;
};

// 保存token
const setToken = function(token) {
  uni.setStorageSync(TOKEN_KEY, token);
};

// 获取 tips
const getTips = function() {
  let userId = getUserId();
  console.log(TIPS_KEY + userId);
  let ret = uni.getStorageSync(TIPS_KEY + userId);
  return ret;
};

// 保存 tips
const setTips = function(count) {
  let userId = getUserId();
  console.log(TIPS_KEY + userId);
  uni.setStorageSync(TIPS_KEY + userId, count);
};
//提出系统
const logout = function() {
  uni.removeStorageSync(USERS_KEY);
  uni.removeStorageSync(TOKEN_KEY);
};

// 获取服务器地址
const getWebsite = function() {
  let website = uni.getStorageSync(WEBSITE);
  return website || "http://";
};

// 设置服务器地址
const setWebsite = function(website) {
  website = website.replace(/：/g, ":");
  website = website.replace(/。/g, ".");
  uni.setStorageSync(WEBSITE, website);
};

// 获取任务列表
const getTaskList = function() {
  let ret = "";
  ret = uni.getStorageSync(TASK_LIST_KEY);
  if (!ret) {
    ret = "[]";
  }
  return JSON.parse(ret);
};

// 设置任务列表
const setTaskList = function(taskList = []) {
  //let taskDetailList = getAllTaskDetail();

  let oldTaskList = getTaskList();

  taskList.forEach(item => {
    oldTaskList.forEach(oldItem => {
      if (oldItem.code.value == item.code.value) {
        if (oldItem.isLoadData) {
          oldItem.isLoadData = "上传";
        }
        item.isLoadData = oldItem.isLoadData;
      }
    });
  });
  uni.setStorageSync(TASK_LIST_KEY, JSON.stringify(taskList));
};

// 按索保存某个任务
const setTaskIndex = function(data, index) {
  let taskList = getTaskList();
  taskList[index] = data;
  uni.setStorageSync(TASK_LIST_KEY, JSON.stringify(taskList));
};

// 获取所有任务的详情数据
const getAllTaskDetail = function() {
  let ret = "";
  ret = uni.getStorageSync(TASK_DETAIL_KEY);
  if (!ret) {
    ret = "{}";
  }
  return JSON.parse(ret);
};

// 获取某个任务详情
const getTaskDetail = function(taskId, dut = false) {
  //console.log(taskId);
  let data = getAllTaskDetail();
  //console.log(data);
  let task = data[taskId];
  if (dut !== false) {
    return task || dut;
  }
  return task;
};

// 设置任务详情
const setTaskDetail = function(taskId, taskData) {
  let data = getAllTaskDetail();
  data[taskId] = taskData;
  uni.setStorageSync(TASK_DETAIL_KEY, JSON.stringify(data));
};

// 获取采样表数据
const getTaskDetailItem = function(taskId, tableId) {
  let data = getAllTaskDetail();
  let tableData = data[taskId] && data[taskId][tableId];
  return tableData;
};

// 设置采样表数据
const setTaskDetailItem = function(taskId, tableId, tableData, field) {
  let data = getAllTaskDetail();
  data[taskId][tableId][field] = tableData[field];
  uni.setStorageSync(TASK_DETAIL_KEY, JSON.stringify(data));
};

// 获取采样表 天数数据
const getTaskDetailDay = function(taskId, tableId, dayNum) {
  let data = getAllTaskDetail();
  let dayData;
  try {
    dayData = data[taskId][tableId]["sample_info"]["value"][dayNum];
    console.log(dayData);
  } catch (e) {
    //TODO handle the exception
    console.log(e);
  }
  return dayData;
};

// 设置采样表 天数数据
const setTaskDetailDay = function(taskId, tableId, dayNum, saveData, field) {
  let data = getAllTaskDetail();
  try {
    data[taskId][tableId]["sample_info"]["value"][dayNum][field] =
      saveData[field];
  } catch (e) {
    //TODO handle the exception
    console.log(e);
  }
  uni.setStorageSync(TASK_DETAIL_KEY, JSON.stringify(data));
};

// 移除文件
const removeFile = function(path) {
  uni.getSavedFileList({
    success: res => {
		console.log(res)
      res.fileList.forEach((item, index) => {
        if (item.filePath == path) {
          uni.removeSavedFile({
            filePath: path,
            complete: res => {
              console.log("删除本地图片");
            }
          });
        }
      });
    }
  });
};

// 保存文件
// #ifdef APP-PLUS || MP-WEIXIN
const saveFile = function(path, oldPath) {
	console.log(path,"------path");
  return new Promise((resolve, ret) => {
    uni.saveFile({
      tempFilePath: path,
      success: saveRes => {
        resolve(saveRes.savedFilePath);
		console.log(oldPath)
        if (
          typeof oldPath == "string" &&
          oldPath.indexOf("original_template") > -1 &&
          oldPath.indexOf("base64") > -1
        ) {
          removeFile(oldPath);
        }
	
      }
    });
  });
};
// #endif

// 保存文件
// #ifdef  H5 
const saveFile = function(path, oldPath) {
  return new Promise((resolve, ret) => {

	 if(path.indexOf("data:image/png;base64") == 0){
		 setTimeout(() => {
		    resolve(path);
		  },50);
	 }else{
		 // resolve(ImgtoBase64(path))
		 console.log(path)
		fetch(`${path}`).then(data=>{
		    const blob = data.blob();
		    return blob;
		}).then(blob=>{
		    let reader = new window.FileReader();
		    
		    reader.onloadend = function() {
		        const data = reader.result;
		        console.log(data);
				resolve(data);
		    };
		
		    reader.readAsDataURL(blob);
		})
		
	 }
  });
};
// #endif

// 图片转base64
const ImgtoBase64 = async function(data, url, success) {
 console.log(data,"我是data_________64");
  let codeId = data.code.value;
// console.log(codeId,"codeid+____")
  let taskData = getTaskDetail(codeId, {});
   console.log(taskData,"_____taskData__64")
  for (let taskId in taskData) {
    let task = taskData[taskId];
    // 表的公共数据
    let commonData = (task.common && task.common.value) || {};
    for (let field in commonData) {
      let item = commonData[field];
      if (item && (item.data_type == 5 || item.data_type == 7) && item.value) {
        await itemIsImg(item);
      }
    }
    // 表尾数据
    let bottomData = (task.bottom && task.bottom.value) || {};
    for (let field in bottomData) {
      let item = bottomData[field];
      if (item && (item.data_type == 5 || item.data_type == 7) && item.value) {
        await itemIsImg(item);
      }
    }
    // 监测点公共数据
    let cydListData = (task.cyd_info && task.cyd_info.value) || {}; // 监测点列表的公共数据
    for (let key in cydListData) {
      let cydData = cydListData[key]; // 单个监测点的数据
      for (let field in cydData) {
        let item = cydData[field];
        if (
          item &&
          (item.data_type == 5 || item.data_type == 7) &&
          item.value
        ) {
          await itemIsImg(item);
        }
      }
    }
    // 样品数据
    let sampleData = (task.sample_info && task.sample_info.value) || {};
    for (let itemId in sampleData) {
      let itemData = sampleData[itemId]; // 单个样品，或 单天的数据

      if (itemData && itemData.cyd_info) {
        // 天数的公共信息
        if (itemData && itemData.common) {
          for (let field in itemData.common) {
            let item = itemData.common[field];
            if (
              item &&
              (item.data_type == 5 || item.data_type == 7) &&
              item.value
            ) {
              await itemIsImg(item);
            }
          }
        }
        // 监测点列表
        for (let point in itemData.cyd_info) {
          let pointSampleList = itemData.cyd_info[point]; // 监测点 样品列表
          for (let key in pointSampleList) {
            let pointSampleItem = pointSampleList[key]; // 单个样品数据
            for (let field in pointSampleItem) {
              let item = pointSampleItem[field];
              if (
                item &&
                (item.data_type == 5 || item.data_type == 7) &&
                item.value
              ) {
                await itemIsImg(item);
              }
            }
          }
        }
      } else {
        for (let field in itemData) {
          let item = itemData[field];
          if (
            item &&
            (item.data_type == 5 || item.data_type == 7) &&
            item.value
          ) {
            await itemIsImg(item);
          }
        }
      }
    }
  }
  return taskData;
};

// 是否是图片
const itemIsImg = function(item) {
  return new Promise((resolve, ret) => {
    let imgTodataURL = function(path) {
      console.log("图片路径: " + path);
      let imgType = path.substring(path.lastIndexOf(".") + 1);
      var d = new Date();
      let tempPath = "_doc/compress/" + d.getTime() + "." + imgType;
      plus.zip.compressImage(
        {
          src: path,
          dst: tempPath,
          overwrite: true,
          quality: 60
        },
        () => {
          try {
            plus.io.resolveLocalFileSystemURL(tempPath, function(entry) {
              entry.file(
                function(file) {
                  let reader = new plus.io.FileReader();
                  reader.onloadend = function(e) {
                    //console.log(e.target.result);
                    item.value = e.target.result;
                    resolve();
                  };
                  reader.readAsDataURL(file);
                },
                function(e) {
                  resolve();
                }
              );
            });
          } catch (e) {
            resolve();
          }
        },
        error => {
          resolve();
        }
      );
    };
    if (
      (typeof item.value == "string" &&
        item.value.indexOf("original_template") > -1) ||
      item.value.indexOf("base64") > -1
    ) {
      item.value = item.value.replace(getWebsite(), "");
      resolve();
    } else {
      imgTodataURL(item.value);
    }
  });
};

export default {
  getUsers,
  addUser,
  getUserName,
  setUserName,
  getWebsite,
  setWebsite,
  getToken,
  setToken,
  getTips,
  setTips,
  getUserId,
  logout,
  getTaskList,
  setTaskList,
  setTaskIndex,
  getTaskDetail,
  setTaskDetail,
  setTaskDetailItem,
  getTaskDetailItem,
  setTaskDetailDay,
  getTaskDetailDay,
  ImgtoBase64,
  removeFile,
  saveFile,
  SAMPLE_TYPE,
  PAGE_DATA
};
